package com.demo.framework.http;

import java.io.ByteArrayOutputStream;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.demo.framework.utils.IOUtils;
import com.demo.framework.utils.StringUtil;

/**
 * 
 * @ClassName: GetHttpDataHelper
 * @Description: TODO(获取数据)
 * @author 谢云腾
 * @date 2013-4-3 上午09:55:58
 * @version 1.0
 */
public class GetHttpDataHelper {

    private String baseUrl = "";

    private List<RequestParameter> parameter;

    private HttpRequest httpRequest = null;

    public GetHttpDataHelper(String baseUrl) {
        this.baseUrl = baseUrl;
        httpRequest = new HttpRequest();
    }

    public void setParameter(List<RequestParameter> parameter) {
        this.parameter = parameter;
    }

    /**
     * 
     * @Title: getHttpData
     * @Description: TODO(根据URL 获取数据)
     * @return String 返回类型
     * @throws
     */
    public String getData() throws HttpException {
        String strData = null;
        if (parameter != null && parameter.size() > 0) {
            StringBuilder bulider = new StringBuilder();
            for (RequestParameter p : parameter) {
                if (bulider.length() != 0) {
                    bulider.append("&");
                }

                bulider.append(StringUtil.encode(p.getName()));
                bulider.append("=");
                bulider.append(StringUtil.encode(p.getValue()));
            }
            baseUrl += "?" + bulider.toString();
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            httpRequest.get(baseUrl, output);
            strData = new String(output.toByteArray());
        }
        catch(Exception e) {
            // TODO: handle exception
        } finally {
            IOUtils.closeQuietly(output);
        }
        return strData;
    }

    /**
     * 获取Json 对象的数据
     */
    public JSONObject getJsonData() throws HttpException {
        String data = getData();
        try {
            return new JSONObject(data);
        }
        catch(JSONException e) {
            // TODO Auto-generated catch block
            throw new HttpException(1, e);
        }
    }

}
